package model;

import essenceClasses.Task;
import interfaceModel.ITaskModel;

import java.sql.*;
import java.sql.Date;
import java.util.*;

/**
 * Created with IntelliJ IDEA.
 * User: Алексей
 * Date: 31.05.14
 * Time: 21:17
 * To change this template use File | Settings | File Templates.
 */
public class TaskModel implements ITaskModel {

    Connection conn = null;


    public TaskModel() {
        conn = Connector.getConnection();

    }



    private static java.sql.Date getCurrentDate(Date createDate) {
        java.util.Date today = new java.util.Date();
        return new java.sql.Date(today.getTime());
    }

    @Override
    public List<Task> getAllTasks() throws SQLException {
        List<Task> list = new LinkedList<Task>();
        Statement statement = conn.createStatement();
        ResultSet resultSet = statement.executeQuery("SELECT * FROM taskdb");
        while (resultSet.next()) {
            //int id, String title, String description, int priorites, Date dateCreate, Date dateStart, Date dateEnd
            list.add(new Task(resultSet.getInt("id"), resultSet.getString("title"), resultSet.getString("description"),
                    resultSet.getInt("priority"), resultSet.getDate("CreateDate"), resultSet.getDate("StartDate"),
                    resultSet.getDate("EndDate")));
        }
        return list;
    }


    @Override
    public boolean addTask(String title, String description, int priority, Date createDate, Date startDate, Date endDate) throws SQLException {
        PreparedStatement preparedStatement = null;

        String insertTaskSQL = "INSERT INTO taskdb"
                + "(title, description, priority, createDate,endDate) VALUES"
                + "(?,?,?,?,?,?)";
        preparedStatement = conn.prepareStatement(insertTaskSQL);
        preparedStatement.setString(1, title);
        preparedStatement.setString(2, description);
        preparedStatement.setInt(3, priority);
        preparedStatement.setDate(4, getCurrentDate(createDate));
        preparedStatement.setDate(5, getCurrentDate(startDate));
        preparedStatement.setDate(6, getCurrentDate(endDate));
        preparedStatement.executeUpdate();
        return true;

    }
}
